<?php

namespace app\admin\controller;

use app\api\model\Order;
use app\common\controller\Backend;
use ba\Random;
use think\facade\Db;
use Throwable;

/**
 * 技师管理
 */
class Technician extends Backend
{
    /**
     * Technician模型对象
     * @var object
     * @phpstan-var \app\admin\model\Technician
     */
    protected object $model;

    protected string|array $defaultSortField = 'technician_id,desc';

    protected array|string $preExcludeFields = ['create_time', 'update_time'];

    protected string|array $quickSearchField = ['technician_id', 'technician_name', 'tel'];

    protected array $noNeedPermission = ['*'];

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Technician;
        $this->request->filter('clean_xss');
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 查看
     * @throws Throwable
     */
    public function index (): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->where($this->isAgentWhere())
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 添加
     */
    public function add (): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }

                $salt = Random::build('alnum', 16);
                $data['salt'] = $salt;
                $data['username'] = $data['tel'];
                $password = $data['password'] ?? '123456';
                $data['password'] = encrypt_password($password, $salt);
                $data['ascription_id'] = $this->ascription_id();
                $data['area_id'] = $this->auth->getInfo()['bind_city_id'];
                $data['intention_city_id'] = $this->auth->getInfo()['bind_city_id'];

                $IDCard_imgs = $data['IDCard_imgs'] ?? "";
                if (is_array($IDCard_imgs)) {
                    $data['IDCard_imgs'] = implode(',', $data['IDCard_imgs']);
                }
                $health_imgs = $data['health_imgs'] ?? "";
                if (is_array($health_imgs)) {
                    $data['health_imgs'] = implode(',', $data['health_imgs']);
                }
                $work_imgs = $data['work_imgs'] ?? "";
                if (is_array($work_imgs)) {
                    $data['work_imgs'] = implode(',', $data['work_imgs']);
                }
                $qualifications = $data['qualifications'] ?? "";
                if (is_array($qualifications)) {
                    $data['qualifications'] = implode(',', $data['qualifications']);
                }


                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 编辑
     * @throws Throwable
     */
    public function edit (): void
    {
        $pk = $this->model->getPk();
        $id = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        #查出技师余额
        $money = Db::name('technician_money_log')
            ->where('technician_id', $id)
            ->order('create_time', 'desc')
            ->value('after') ?? 0;
        $row->money = sprintf('%.2f', $money);

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }

//                if ($row->username != $data['tel']) {
//                    $data['username'] = $data['tel'];
//                }

                if (empty($data['password'])) {
                    unset($data['password']);
                } else {
                    $salt = Random::build('alnum', 16);
                    $data['salt'] = $salt;
                    $data['password'] = encrypt_password($data['password'], $salt);
                }
                $IDCard_imgs = $data['IDCard_imgs'] ?? "";
                if (is_array($IDCard_imgs)) {
                    $data['IDCard_imgs'] = implode(',', $data['IDCard_imgs']);
                }
                $health_imgs = $data['health_imgs'] ?? "";
                if (is_array($health_imgs)) {
                    $data['health_imgs'] = implode(',', $data['health_imgs']);
                }
                $work_imgs = $data['work_imgs'] ?? "";
                if (is_array($work_imgs)) {
                    $data['work_imgs'] = implode(',', $data['work_imgs']);
                }
                $qualifications = $data['qualifications'] ?? "";
                if (is_array($qualifications)) {
                    $data['qualifications'] = implode(',', $data['qualifications']);
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 获取服务记录
     */
    public function serviceLog ()
    {
        $technician_id = $this->request->param('technician_id');
        $limit = $this->request->param('limit');

        $info = Order::with(['service'])
            ->field('id,order_sn,order_state,service_num,service_reality_price,service_start_time,create_time,service_id')->
            where('technician_id', $technician_id)->order('create_time', 'desc')->paginate($limit)->each(function ($item) {
                $item->order_state_text = $item->order_state_text;
                return $item;
            });
        $this->success('',
            ['list'  => $info->items(),
             'total' => $info->total(),
            ]
        );
    }

    /**
     * 获取技师余额变动记录
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function balanceEditLog ()
    {
        $technician_id = $this->request->param('technician_id');
        $limit = $this->request->param('limit');
        $info = Db::name('technician_money_log')
            ->alias('log')
            ->join('order', 'order.id = log.order_id', 'LEFT')
            ->field('log.*,order.order_sn')
            ->where('log.technician_id', $technician_id)
            ->order('log.create_time', 'desc')
            ->paginate($limit);
        $this->success('',
            ['list'  => $info->items(),
             'total' => $info->total(),
            ]
        );
    }


    /**
     * 修改余额
     * @return void
     */
    public function addBalanceLog ()
    {
        $post = $this->request->post();

        $technicianInfo = Db::name('technician_money_log')->where('technician_id', $post['technician_id'])->find();

        $technicianInfoAfter = $technicianInfo['after'] ?? 0;
        if ($post['type'] == 4) {
            $after = bcadd($post['money'], $technicianInfoAfter, 2);
        } else {
            $after = bcsub($technicianInfoAfter, $post['money'], 2);
        }

        $ret = Db::name('technician_money_log')->insert([
            'technician_id' => $post['technician_id'],
            'before'        => $technicianInfoAfter,
            'after'         => $after,
            'money'         => $post['money'],
            'memo'          => $post['memo'],
            'order_id'      => 0,
            'type'          => $post['type'],
            'create_time'   => date('Y-m-d H:i:s', time()),
        ]);
        if (!$ret) {
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }

    public function agree ()
    {
        $technician_id = $this->request->get('technician_id');

        $info = $this->model->where('technician_id', $technician_id)->find();
        $info->is_go_work = 2;
        $info->status = 1;
        $info->is_travel = 0;
        if (!$info->save()) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
    public function getEvaluateLog ()
    {
        $technician_id = $this->request->get('technician_id');

        $technicianInfo = Db::name('order_evaluate')->where('
        technician_id', $technician_id)->order('create_time', 'desc')->paginate();
        $this->success('', ['list' => $technicianInfo->items(), 'total' => $technicianInfo->total()]);
    }
}